import {
  ActionType,
  ProColumns,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, Dropdown, Input, InputNumber, message, Space } from 'antd';
import { useRef, useState } from 'react';
import CreateForm from '@/components/CreateForm';
import services from '@/services/invoices';
import MaterialWin from './components/material';
import React from 'react';
import { DownOutlined } from '@ant-design/icons';


const { queryList, addData, modifyData, deleteData } = services.InvoicesController

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (id: number | string | null = null, fields: API.Invoices) => {
  const hide = message.loading('正在操作');
  try {
    id ? await modifyData({ id }, { ...fields }) : await addData({ ...fields });
    hide();
    message.success('操作成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.Invoices[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await deleteData({
      id: selectedRows.find((row) => row.id)?.id || '',
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const InvoicesList = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [winProps, setWindowProps] = useState<any>({ title: '新建', id: null, record: {}, width: 1200 })
  const [materialProps, setMaterialProps] = useState<any>({ modalVisible: false, title: '物料信息', id: null, width: 1000 })
  const [approveProps, setApproveProps] = useState<any>({ modalVisible: false, title: '审批信息', id: null, width: 1000 })
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const columns: any = [
    {
      title: '发票类型',
      dataIndex: 'invoiceType',
      key: 'invoiceType',
      valueType: 'text', // valueType 属性可以根据需要更改为 'money'、'date' 或其他适当的值
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },

    {
      title: '发票代码',
      dataIndex: 'invoiceNumber',
      key: 'invoiceNumber',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '发票号码',
      dataIndex: 'invoiceNo',
      key: 'invoiceNo',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '校验码',
      dataIndex: 'verificationCode',
      key: 'verificationCode',
      valueType: 'text',
      ellipsis: true, width: 200,
    },
    {
      title: '开票日期',
      dataIndex: 'invoiceDate',
      key: 'invoiceDate',
      valueType: 'date',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '购买方公司名称',
      dataIndex: 'buyerCompanyName',
      key: 'buyerCompanyName',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '购买方纳税人识别号',
      dataIndex: 'buyerTaxID',
      key: 'buyerTaxID',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '购买方地址、电话',
      dataIndex: 'buyerAddressAndPhone',
      key: 'buyerAddressAndPhone',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '购买方开户行及账号',
      dataIndex: 'buyerBankAndAccount',
      key: 'buyerBankAndAccount',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },

    {
      title: '价税合计(大写)',
      dataIndex: 'totalAmountInWords',
      key: 'totalAmountInWords',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '价税合计(小写)',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      valueType: 'money',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '销售方公司名称',
      dataIndex: 'sellerCompanyName',
      key: 'sellerCompanyName',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '销售方纳税人识别号',
      dataIndex: 'sellerTaxID',
      key: 'sellerTaxID',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '销售方地址、电话',
      dataIndex: 'sellerAddressAndPhone',
      key: 'sellerAddressAndPhone',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '销售方开户行及账号',
      dataIndex: 'sellerBankAndAccount',
      key: 'sellerBankAndAccount',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '备注',
      dataIndex: 'note',
      key: 'note',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    // {
    //   title: '印刷公司',
    //   dataIndex: 'printingCompany',
    //   key: 'printingCompany',
    //   valueType: 'text',
    //   ellipsis: true, width: 200,
    //   formitemprops: {
    //     rules: [
    //       {
    //         required: true,
    //         message: '必填项',
    //       },
    //     ],
    //   },
    // },
    {
      title: '收款人',
      dataIndex: 'payee',
      key: 'payee',
      valueType: 'text',
      ellipsis: true, width: 100,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '复核人',
      dataIndex: 'reviewer',
      key: 'reviewer',
      valueType: 'text',
      ellipsis: true, width: 100,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
      valueType: 'text',
      ellipsis: true, width: 200,
      formitemprops: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
      renderFormItem: () => {
        return <Input.TextArea allowClear />
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_: any, record: { id: any; invoiceType: string }) => (
        <>
          <a
            onClick={() => {
              setWindowProps({ ...winProps, title: '编辑', id: record.id, record, width: 1200 })
              handleModalVisible(true)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
            setMaterialProps({ ...materialProps, modalVisible: true, title: '参保记录', id: record.id, record, width: 1000 })
          }}>费用项</a>
          <Divider type="vertical" />
          <Dropdown menu={{
            items: [
              {
                label: <a href={`/epticekt.html?id=${record.id}`} target='_blank'>电子专票</a>,
                key: '1',
              },
              {
                type: 'divider',
              },
              {
                label: <a href={`/ezticekt.html?id=${record.id}`} target='_blank'>电子普票</a>,
                key: '2',
              },
              {
                type: 'divider',
              },
              {
                label: <a href={`/zticekt_dark.html?id=${record.id}`} target='_blank'>专票黑色</a>,
                key: '3',
              },
              {
                type: 'divider',
              },
              {
                label: <a href={`/zticekt_green.html?id=${record.id}`} target='_blank'>专票绿色</a>,
                key: '4',
              },
              {
                type: 'divider',
              },
            ]
          }} trigger={['click']}>
            <a onClick={(e) => e.preventDefault()}>
              <Space>
                导出预览
                <DownOutlined />
              </Space>
            </a>
          </Dropdown>
        </>
      ),
    },
  ];
  function generateRandomPasswordArea() {
    const operators = ['+', '-', '*', '/', '>', '<'];
    let passwordArea = '';

    let count = 0;
    while (count < 100) {
      const numberCount = Math.floor(Math.random() * 4) + 1; // 生成 1 到 4 之间的数字数量
      for (let i = 0; i < numberCount; i++) {
        const number = Math.floor(Math.random() * 10);
        passwordArea += number;
        count++;

        // 在数字后面添加运算符（最后一个数字后不添加运算符）
        if (i < numberCount - 1) {
          passwordArea += operators[Math.floor(Math.random() * operators.length)];
        }
      }
    }
    return passwordArea;
  }
  return (
    <PageContainer
      header={{
        title: '发票管理',
      }}
    >
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        scroll={{ x: 1800 }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              setWindowProps({ ...winProps, title: '新建', id: null, record: { password: generateRandomPasswordArea() }, width: 1200 })
              handleModalVisible(true)
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params) => {
          const { data, success, total } = await queryList({
            ...params,
          });
          return {
            data: data || [],
            success,
            total
          };
        }}
        columns={columns}
        rowSelection={{
          type: 'radio',
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}
      <CreateForm
        onCancel={() => {
          handleModalVisible(false)
        }}
        modalVisible={createModalVisible}
        {...winProps}
      >
        <ProTable<API.Invoices, API.Invoices>
          onSubmit={async (value) => {
            const success = await handleAdd(winProps.id, value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}

          rowKey="id"
          type="form"
          form={{
            initialValues: winProps.record,
            layout: 'inline',
            labelCol: { style: { width: 180, margin: 4 } },
            wrapperCol: { style: { margin: 4, minWidth: 300 }, span: 16 },
            labelAlign: 'left',
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        onCancel={() => {
          setMaterialProps({})
        }}
        {...materialProps}
      >
        <MaterialWin id={materialProps.id} />
      </CreateForm>
    </PageContainer>

  );
}

export default InvoicesList;